﻿using UnityEngine;
using System.Collections;
using UnityEngine.Events;


public class Alien : MonoBehaviour {

	public Transform target;
	private NavMeshAgent agent;

	public float navigationUpdateTime;
	private float navigationTime = 0;

	public Rigidbody head;
	private bool isAlive = true;

	//event
	public UnityEvent OnDestroy;

	//particle
	private DeathParticles deathParticle;

	// Use this for initialization
	void Start () {
		agent = GetComponent<NavMeshAgent> ();
	}
	
	// Update is called once per frame
	void Update () {
		if (!isAlive) return;

		navigationTime += Time.deltaTime;
		if (navigationTime < navigationUpdateTime) {
			navigationTime = 0;

			if (target) {
				agent.destination = target.position;
			}
		}
	}

	void OnTriggerEnter(Collider other) {
		if (isAlive) {
			Die ();
			SoundManager.Instance.PlayOneShot (SoundManager.Instance.alienDeath);
		}
	}

	public void Die() {
		isAlive = false;
		head.GetComponent<Animator> ().enabled = false;
		head.transform.parent = null;
		head.useGravity = true;
		head.isKinematic = false;
		head.GetComponent<SphereCollider> ().enabled = true;
		head.velocity = new Vector3 (0.0f, 26.0f, 3.0f);
		head.GetComponent<SelfDestruct> ().Initiate ();

		if (deathParticle) {
			deathParticle.transform.parent = null;
			deathParticle.Active ();
		}

		OnDestroy.Invoke ();
		OnDestroy.RemoveAllListeners ();
		Destroy (gameObject);
	}

	public DeathParticles GetDeathParticle() {
		if (deathParticle == null) {
			deathParticle = GetComponentInChildren<DeathParticles> ();
		}
		return deathParticle;
	}
}
